<template>
  <zh-form
      :span="24"
      style="width: 100%"
      ref="rolePageFrom"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
      :rules="rules"
  >
    <zh-row>
      <zh-input
          prop="h2507"
          :disabled="editFlag"
          type="number"
          label="序号"
          :labelCol="{ style: 'width: 100px;float: left' }"
          v-model="mediaInfoItem.h2507"
      />

      <zh-input
          prop="h2503"
          :disabled="editFlag"
          type="text"
          label="名称"
          :labelCol="{ style: 'width: 100px;float: left' }"
          v-model="mediaInfoItem.h2503"
          @blur="blurh2502Name(mediaInfoItem)"
      />
      <zh-input
          v-if="mediaInfoItem.h2502Name === '全景'"
          prop="h2504"
          :disabled="editFlag"
          type="text"
          label="链接填写"
          :labelCol="{ style: 'width: 100px;float: left' }"
          v-model="mediaInfoItem.h2504"
      />
      <div
          v-if="mediaInfoItem.h2502Name && mediaInfoItem.h2502Name !== '图片'"
          class="r-item"
      >
        <zh-upload
            :disabled="editFlag"
            :defaultImageList="mediaInfoItem.fileList"
            label="缩略图"
            :labelLh="false"
            :labelCol="{ style: 'width: 100px;float: left' }"
            @handleChange="
            (file) => {
              return handleRange(file, '1');
            }
          "
        />
      </div>

      <div
          v-if="mediaInfoItem.h2502Name !== '全景'"
          class="r-item"
          :class="[mediaInfoItem.h2502Name === '图片' ? 'r-pictrue' : 'r-media']"
      >
        <a-upload
            title="媒体信息"
            :disabled="editFlag"
            list-type="picture"
            :file-list="mediaInfoItem.mediaList"
            :remove="handleRemove"
            :customRequest="
            (file) => {
              return handleRangeAfter(file);
            }
          "
        >
          <ep-button
              v-if="
              mediaInfoItem.h2502Name === '图片' ||
              mediaInfoItem.h2502Name === undefined
            "
              size="small"
              style="margin-left: 100px; margin-bottom: 5px"
          >
            文件上传
          </ep-button>
          <ep-button
              v-if="
              mediaInfoItem.h2502Name === '视频' ||
              mediaInfoItem.h2502Name === '音频'
            "
              size="small"
              style="margin-left: 100px; margin-bottom: 5px"
          >
            文件上传（建议mp4或其他）
          </ep-button>
          <span v-if="mediaInfoItem.h2502Name === '视频'" style="color: red">
            (上传大小请控制在50M以内)</span
          >
        </a-upload>
      </div>
    </zh-row>
    <a-modal
        :closable="false"
        footer=""
        :maskClosable="false"
        v-model="showUploadingModal"
    >
      <div style="text-align: center">
        <a-spin size="large" tip="文件上传中..."></a-spin>
      </div>
    </a-modal>
  </zh-form>
</template>

<script>
import {
  fileDownloadUrl,
  fileShowUrl,
  fileUploadUrl,
  getBatchDict,
} from "@/services/system/api";
import modal from "ant-design-vue/es/modal";
import imgTypeChange from "@/utils/imgTypeChange";

export default {
  data() {
    return {
      mediaInfoItem: {
        h2501: "",
        h2502: "",
        h2502Name: undefined,
        h2503: "",
        h2504: "",
        h2505: "",
        h2506: "",
        h2507: 0,
        fileList: [],
        mediaList: [],
      },
      dictData: {},
      editFlag: true,
      h2507Num: 0,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      h2502Name: "",
      fileShowUrl: fileShowUrl, //预览接口地址
      rules: {

      },
      showUploadingModal: false,
    };
  },
  created() {
    this.init();
  },
  methods: {
    blurh2502Name(row) {
      if (row.h2501) {
        row.flag = "edit";
      }
    },
    init(row) {
      const params = {};
      params.dictFields = "B0202";
      this.$http.post(getBatchDict, params).then((res) => {
        let resultData = JSON.parse(JSON.stringify(this.dictData));
        resultData.h2502 = res.result.B0202;
        this.dictData = resultData;
      });
      if (row !== undefined && row !== null) {
        if (row.b0201) {
          row.fileList = [
            {
              url: this.fileShowUrl + row.h2506,
              name: row.h2506,
              showId: row.h2506,
              fileOrigUrl: row.h2506,
              uid: row.h2506,
              status: "done",
              fileOrigType: "",
            },
          ];
        } else {
          row.fileList = [];
        }
        if (row.h2504) {
          let showId = row.h2504;
          row.mediaList = [
            {
              url: //this.fileShowUrl+showId,
                  row.h2502Name === "图片"
                      ? this.fileShowUrl + showId
                      : require("@/assets/img/icon-file.png"),
              name: row.h2505,
              showId: showId,
              fileOrigUrl: showId,
              uid: showId,
              status: "done",
              fileOrigType: "",
            },
          ];
        } else {
          row.mediaList = [];
        }
        this.mediaInfoItem = JSON.parse(JSON.stringify(row));
      } else {
        this.clean();
      }
    },
    clean() {
      this.mediaInfoItem = {
        h2501: "",
        h2502: "",
        h2502Name: undefined,
        h2503: "",
        h2504: "",
        h2505: "",
        h2506: "",
        h2507: this.h2507Num,
        fileList: [],
        mediaList: [],
      };
    },
    handleRangeAfter(data) {
      this.showUploadingModal = true;
      this.handleRange(data);
    },
    async handleRange(data, type) {
      if (data.file) {
        if (data.file.size / (1024 * 1024) > 50) {
          modal.error({
            title: "错误",
            content: "上传失败，文件大小不能超过50M",
          });
          this.showUploadingModal = false;
          return;
        }
        let flag = false;
        //大于3mb进行压缩
        if (data.file.size / (1024 * 1024) > 3) {
          flag = true;
        }
        //获取后缀带"."
        let type1 = data.file.name.substr(data.file.name.lastIndexOf("."));
        if (type1 === ".png") {
          let myFile = await imgTypeChange(data.file);
          await this.compressImg(myFile, data, type, this, flag);
        } else {
          await this.compressImg(data.file, data, type, this, flag);
        }
      } else if (data[0].showId) {
        if (type === "1") {
          this.mediaInfoItem.h2506 = data[0].showId;
          this.mediaInfoItem.showId = data[0].showId;
        } else {
          let showId = data[0].showId;
          this.mediaInfoItem.h2504 = showId;
          this.mediaInfoItem.h2505 = data[0].name;
          this.mediaInfoItem.mediaList = [
            {
              url:
                  this.mediaInfoItem.h2502Name === "图片"
                      ? this.fileShowUrl + showId
                      : require("@/assets/img/icon-file.png"),
              name: data[0].name,
              showId: showId,
              fileOrigUrl: showId,
              uid: showId,
              status: "done",
              fileOrigType: "",
            },
          ];
        }
      }
    },
    afterUpload(dateFile, data, type) {
      data.file = dateFile;
      const params = new FormData();
      params.append("file", data.file);
      params.append("fileClassCode", "99"); //文件分类 20：小程序 10:pc申报  11：pc审核
      params.append("uploaderId", this.$store.state.user.userInfo.userId);
      params.append("uploader", "true"); //是否按上传人uploaderId生成不同的showId
      this.$http
          .post(fileUploadUrl, params)
          .then((res) => {
            if (type === "1") {
              this.mediaInfoItem.h2506 = res.result.file.showId;
              this.mediaInfoItem.showId = res.result.file.showId;
            } else {
              let showId = res.result.file.showId;
              this.mediaInfoItem.h2504 = showId;
              this.mediaInfoItem.h2505 = dateFile.name;
              this.mediaInfoItem.mediaList = [
                {
                  url:
                      this.mediaInfoItem.h2502Name === "图片"
                          ? this.fileShowUrl + showId
                          : require("@/assets/img/icon-file.png"),
                  name: dateFile.name,
                  showId: showId,
                  fileOrigUrl: showId,
                  uid: showId,
                  status: "done",
                  fileOrigType: "",
                },
              ];
            }
            this.$forceUpdate(); //重新强制渲染
            data.onSuccess(res, data.file);
            this.showUploadingModal = false;
            this.$message.success("文件上传成功");
          })
          .catch((res) => {
            console.log(res);
            modal.error({ title: "错误", content: "文件上传失败" });
          });
    },
    //压缩图片
    compressImg(file, data, type, that, flag) {
      //flag 是否压缩标识
      const reg = /\.(png|jpg|gif|jpeg|webp|PNG|JPG|JPEG)$/;
      if (!flag || !reg.test(file.name)) {
        that.afterUpload(file, data, type);
        return;
      }
      //支持压缩的格式
      if (reg.test(file.name)) {
        //压缩倍率参数
        var quality = 0.5;
        var name = file.name;
        var src;
        var files;
        var fileSize = parseFloat(parseInt(file["size"]) / 1024 / 1024).toFixed(
            2
        );
        var read = new FileReader();
        read.readAsDataURL(file);
        return new Promise(function (resolve, reject) {
          read.onload = function (e) {
            var img = new Image();
            img.src = e.target.result;
            img.onload = async function () {
              //默认按比例压缩
              var w = this.width,
                  h = this.height;
              //生成canvas
              var canvas = document.createElement("canvas");
              var ctx = canvas.getContext("2d");
              var base64;
              // 创建属性节点
              canvas.setAttribute("width", w);
              canvas.setAttribute("height", h);
              ctx.drawImage(this, 0, 0, w, h);
              if (fileSize) {
                //所有图片压缩一半
                base64 = canvas.toDataURL(file["type"], quality);
              }
              // 回调函数返回file的值（将base64编码转成file）
              let arr = base64.split(",");
              let mime = arr[0].match(/:(.*?);/)[1];
              let bytes = atob(arr[1]); // 解码base64
              let n = bytes.length;
              let ia = new Uint8Array(n);
              while (n--) {
                ia[n] = bytes.charCodeAt(n);
              }
              files = new File([ia], name, { type: mime });
              // 以服务的方式调用的 Loading 需要异步关闭
              // setTimeout( () => {
              // loadingInstance.close()
              // }, 500 )
              //("files",files)
              that.afterUpload(files, data, type);
            };
          };
        });
      }
    },
    methodChange(val) {
      if (this.mediaInfoItem.h2501) {
        this.mediaInfoItem.flag = "edit";
      }
      for (let item of this.dictData.h2502) {
        if (item.dictKey === val) {
          this.mediaInfoItem.h2502Name = item.dictValue;
          break;
        }
      }
      this.mediaInfoItem = {
        h2501: this.mediaInfoItem.h2501,
        b0101: "",
        h2502: val,
        h2502Name: this.mediaInfoItem.h2502Name,
        h2503: "",
        h2507: this.mediaInfoItem.h2507,
        h2504: "",
        h2505: "",
        h2506: "",
        fileList: [],
        mediaList: [],
      };
      if (
          this.mediaInfoItem.h2502Name === "视频" ||
          this.mediaInfoItem.h2502Name === "音频"
      ) {
        let showId =
            this.mediaInfoItem.h2502Name === "视频"
                ? "7e0bb99fce9b4e2381fbf945d951fc28"
                : "9395b6dec6234785863fb4cb3d0af924";
        this.mediaInfoItem.h2506 = showId;
        this.mediaInfoItem.fileList = [
          {
            url: this.fileShowUrl + showId,
            name: showId,
            showId: showId,
            fileOrigUrl: showId,
            uid: showId,
            status: "done",
            fileOrigType: "",
          },
        ];
      }
    },
    handleRemove() {
      this.mediaInfoItem.h2504 = "";
      this.mediaInfoItem.h2505 = "";
      this.mediaInfoItem.mediaList = [];
      return true;
    },
  },
};
</script>
<style lang="less" scoped>
.r-item {
  display: block;
  width: 100%;
}
.r-pictrue,
.r-media {
  ::v-deep .ant-upload-list-item {
    border: none !important;
    margin-left: 100px;
    margin-top: 16px;
    padding: 0;
    .ant-upload-list-item-info {
      > span {
        display: flex;
        align-items: center;
        .ant-upload-list-item-thumbnail {
          flex: 0 0 auto;
          width: 208px;
          position: static;
          left: 0;
          top: 0;
          height: 100%;
          img {
            width: 100%;
            height: 100%;
            vertical-align: middle;
          }
        }
        .ant-upload-list-item-name {
          position: static;
          flex: 0 0 auto;
          max-width: auto;
          width: auto;
          margin: 0;
          padding: 0 15px 0 10px;
        }
        .ant-upload-list-item-card-actions {
          position: static !important;
          top: 0 !important;
          flex: 0 0 auto;
          .anticon {
            color: #f5222d;
            svg {
              width: 18px;
              height: 18px;
            }
          }
        }
      }
    }
  }
}
.r-media {
  ::v-deep .ant-upload-list-item {
    .ant-upload-list-item-thumbnail {
      width: 104px !important;
    }
  }
}
::v-deep .ant-upload-select-picture-card {
  width: 104px;
  height: 104px !important;
}
::v-deep .ant-upload-list-item {
  height: 104px !important;
}
</style>
